package com.qyhl.webtv.module_news.news.union.town.meetingroom;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.qyhl.cloud.webtv.module_news.R;
import com.qyhl.cloud.webtv.module_news.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.glide.GlideCircleTransform;
import com.qyhl.webtv.basiclib.utils.glide.GlideRoundTransform;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.news.MeetingRoomListBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.imagebrowser.MNImageBrowser;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.adapter.recyclerview.wrapper.EmptyWrapper;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import es.dmoral.toasty.Toasty;

/**
 * Created by qyhl on 2018/3/1.
 * 议事厅
 */
@Route(path = ARouterPathConstant.MEETING_ROOM)
public class MeetingRoomActivity extends BaseActivity implements MeetingRoomContract.MeetingRoomView {
    @BindView(R2.id.mtitle)
    TextView mTitle;
    @BindView(R2.id.mtoolbar)
    Toolbar mToolbar;
    @BindView(R2.id.mrecyclerView)
    RecyclerView mRecyclerView;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;

    private MeetingRoomPresenter mPresenter;

    @Autowired(name = "id")
    String streetId;

    private String meetingId = "0";

    @Autowired(name ="rule")
    String rule;

    private EmptyWrapper emptyWrapper;
    private CommonAdapter mAdapter;
    @Autowired(name = "title")
    String meetingName;

    private List<MeetingRoomListBean> mDataList;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected int getContentView() {
        return R.layout.news_activity_meeting_room;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new MeetingRoomPresenter(this);
        initView();

    }

    @Override
    protected void setListener() {
        setListeners();
        mPresenter.getMeetingList(streetId, meetingId);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.news_circle_topic_menu, menu);
        menu.findItem(R.id.add_circle_white).setVisible(false);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int i = item.getItemId();
        if (i == R.id.add_circle) {

            CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                @Override
                public void login(boolean isLogin) {
                    if( isLogin ){
                        Bundle bundle = new Bundle();
                        bundle.putString("id", streetId);
                        bundle.putString("rule", rule);
                        RouterManager.router(MeetingRoomActivity.this,ARouterPathConstant.ADD_MEETING, bundle, 200);
                    }else{
                        RouterManager.routerLogin(MeetingRoomActivity.this, 0);
                    }
                }

                @Override
                public void error(String s) {

                }
            });



        } else if (i == android.R.id.home) {
            finish();
        } else {
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 初始化
     */
    private void initView() {
        loadMask.setStatus(LoadingLayout.Loading);
        mDataList = new ArrayList<>();
        mTitle.setText(meetingName == null ? "民主议事" : meetingName);
        mToolbar.setTitle("");
        setSupportActionBar(mToolbar);

        refresh.setRefreshHeader(new MaterialHeader(this));
        refresh.setRefreshFooter(new ClassicsFooter(this));
        refresh.setEnableLoadMore(true);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        //添加自定义分割线
        DividerItemDecoration divider = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(this, R.drawable.news_recycleview_divider));
        mRecyclerView.addItemDecoration(divider);

        mAdapter = new CommonAdapter<MeetingRoomListBean>(this, R.layout.news_item_meeting_room, mDataList) {

            @Override
            protected void convert(ViewHolder holder, MeetingRoomListBean bean, int position) {
                ImageView headIcon = holder.getView(R.id.head_icon);
                TextView nickName = holder.getView(R.id.nickname);
                TextView publishDate = holder.getView(R.id.publish_date);
                TextView summary = holder.getView(R.id.summary);

                Glide.with(MeetingRoomActivity.this)
                        .load(bean.getMeetingMessage().getUserAvatar())
                        .apply(new RequestOptions().placeholder(R.drawable.comment_head_default).error(R.drawable.comment_head_default).transform(new GlideCircleTransform(MeetingRoomActivity.this)))
                        .into(headIcon);

                nickName.setText(bean.getMeetingMessage().getNickName());

                publishDate.setText(DateUtils.mTranslateDate(bean.getMeetingMessage().getCreateTime()));

                summary.setText(bean.getMeetingMessage().getContent());

                LinearLayout image_layout = holder.getView(R.id.image_layout);

                ImageView image_one = holder.getView(R.id.image_one);
                final CardView image_one_layout = holder.getView(R.id.image_one_layout);
                image_one_layout.setTag(bean);

                ImageView image_two = holder.getView(R.id.image_two);
                final CardView image_two_layout = holder.getView(R.id.image_two_layout);
                image_two_layout.setTag(bean);

                ImageView image_three = holder.getView(R.id.image_three);
                final CardView image_three_layout = holder.getView(R.id.image_three_layout);
                image_three_layout.setTag(bean);

                TextView photo_tag = holder.getView(R.id.photo_tag);

                image_one_layout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        MeetingRoomListBean bean = (MeetingRoomListBean) v.getTag();
                        MNImageBrowser.showImageBrowser(MeetingRoomActivity.this, image_one_layout, 0, getImageList(bean));
                    }
                });
                image_two_layout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        MeetingRoomListBean bean = (MeetingRoomListBean) v.getTag();
                        MNImageBrowser.showImageBrowser(MeetingRoomActivity.this, image_two_layout, 1, getImageList(bean));
                    }
                });
                image_three_layout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        MeetingRoomListBean bean = (MeetingRoomListBean) v.getTag();
                        MNImageBrowser.showImageBrowser(MeetingRoomActivity.this, image_three_layout, 2, getImageList(bean));
                    }
                });

                switch (bean.getImages().size()) {
                    case 0:
                        image_layout.setVisibility(View.GONE);
                        break;
                    case 1:
                        image_layout.setVisibility(View.VISIBLE);
                        image_one_layout.setVisibility(View.VISIBLE);
                        image_two_layout.setVisibility(View.INVISIBLE);
                        image_three_layout.setVisibility(View.INVISIBLE);
                        photo_tag.setVisibility(View.GONE);
                        Glide.with(MeetingRoomActivity.this)
                                .load(bean.getImages().get(0).getUrl())
                                .apply(new RequestOptions().placeholder(R.drawable.cover_normal_default).error(R.drawable.cover_normal_default).optionalTransform(new GlideRoundTransform(4)))
                                .into(image_one);
                        break;
                    case 2:
                        image_layout.setVisibility(View.VISIBLE);
                        image_one_layout.setVisibility(View.VISIBLE);
                        image_two_layout.setVisibility(View.VISIBLE);
                        image_three_layout.setVisibility(View.INVISIBLE);
                        photo_tag.setVisibility(View.GONE);
                        Glide.with(MeetingRoomActivity.this)
                                .load(bean.getImages().get(0).getUrl())
                                .apply(new RequestOptions().placeholder(R.drawable.cover_normal_default).error(R.drawable.cover_normal_default).optionalTransform(new GlideRoundTransform(4)))
                                .into(image_one);
                        Glide.with(MeetingRoomActivity.this)
                                .load(bean.getImages().get(1).getUrl())
                                .apply(new RequestOptions().placeholder(R.drawable.cover_normal_default).error(R.drawable.cover_normal_default).optionalTransform(new GlideRoundTransform(4)))
                                .into(image_two);
                        break;
                    case 3:
                        image_layout.setVisibility(View.VISIBLE);
                        image_one_layout.setVisibility(View.VISIBLE);
                        image_two_layout.setVisibility(View.VISIBLE);
                        image_three_layout.setVisibility(View.VISIBLE);
                        photo_tag.setVisibility(View.GONE);
                        Glide.with(MeetingRoomActivity.this)
                                .load(bean.getImages().get(0).getUrl())
                                .apply(new RequestOptions().placeholder(R.drawable.cover_normal_default).error(R.drawable.cover_normal_default).optionalTransform(new GlideRoundTransform(4)))
                                .into(image_one);
                        Glide.with(MeetingRoomActivity.this)
                                .load(bean.getImages().get(1).getUrl())
                                .apply(new RequestOptions().placeholder(R.drawable.cover_normal_default).error(R.drawable.cover_normal_default).optionalTransform(new GlideRoundTransform(4)))
                                .into(image_two);
                        Glide.with(MeetingRoomActivity.this)
                                .load(bean.getImages().get(2).getUrl())
                                .apply(new RequestOptions().placeholder(R.drawable.cover_normal_default).error(R.drawable.cover_normal_default).optionalTransform(new GlideRoundTransform(4)))
                                .into(image_three);
                        break;
                    default:
                        image_layout.setVisibility(View.VISIBLE);
                        image_one_layout.setVisibility(View.VISIBLE);
                        image_two_layout.setVisibility(View.VISIBLE);
                        image_three_layout.setVisibility(View.VISIBLE);
                        photo_tag.setVisibility(View.VISIBLE);
                        Glide.with(MeetingRoomActivity.this)
                                .load(bean.getImages().get(0).getUrl())
                                .apply(new RequestOptions().placeholder(R.drawable.cover_normal_default).error(R.drawable.cover_normal_default).optionalTransform(new GlideRoundTransform(4)))
                                .into(image_one);
                        Glide.with(MeetingRoomActivity.this)
                                .load(bean.getImages().get(1).getUrl())
                                .apply(new RequestOptions().placeholder(R.drawable.cover_normal_default).error(R.drawable.cover_normal_default).optionalTransform(new GlideRoundTransform(4)))
                                .into(image_two);
                        Glide.with(MeetingRoomActivity.this)
                                .load(bean.getImages().get(2).getUrl())
                                .apply(new RequestOptions().placeholder(R.drawable.cover_normal_default).error(R.drawable.cover_normal_default).optionalTransform(new GlideRoundTransform(4)))
                                .into(image_three);

                        photo_tag.setText("共" + bean.getImages().size() + "张");
                        break;
                }

//                if (bean.getImages() != null && bean.getImages().size() > 0) {
//                    nineLayout.setVisibility(View.VISIBLE);
//                    nineLayout.setGap(10);
//                    final List<Image> imageList = initDatas(bean.getImages());
//                    Adapter adapter = new Adapter(MeetingRoomActivity.this, imageList);
//                    nineLayout.setAdapter(adapter);
//                    nineLayout.setOnItemClickListerner(new NineLayout.OnItemClickListerner() {
//                        @Override
//                        public void onItemClick(View view, int position) {
//
//                            ArrayList<String> mList = new ArrayList<>();
//                            for (int i = 0; i < imageList.size(); i++) {
//                                mList.add(imageList.get(i).getUrl());
//                            }
//                            MNImageBrowser.showImageBrowser(MeetingRoomActivity.this, view, position, mList);
//                        }
//                    });
//                } else {
//                    nineLayout.setVisibility(View.GONE);
//                }

            }
        };

        emptyWrapper = new EmptyWrapper(mAdapter);
        emptyWrapper.setEmptyView(R.layout.news_layout_common_emptyview);
        mRecyclerView.setAdapter(emptyWrapper);

    }

    private ArrayList<String> getImageList(MeetingRoomListBean bean) {
        ArrayList<String> result = new ArrayList<>();
        for (int i = 0; i < bean.getImages().size(); i++) {
            result.add(bean.getImages().get(i).getUrl());
        }
        return result;
    }

    /**
     * 设置监听
     */
    private void setListeners() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                meetingId = "0";
                loadMask.setReloadButtonText("加载中...");
                mPresenter.getMeetingList(streetId, meetingId);
            }
        });

        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                meetingId = "0";
                mPresenter.getMeetingList(streetId, meetingId);
            }
        });

        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                mPresenter.getMeetingList(streetId, meetingId);
            }
        });
    }

    /**
     * 获取数据成功
     *
     * @param beanList
     * @param isMore
     */
    @Override
    public void getListSuccess(List<MeetingRoomListBean> beanList, boolean isMore) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~~");
        if (beanList != null && beanList.size() > 0) {
            meetingId = beanList.get(beanList.size() - 1).getMeetingMessage().getId() + "";
        }
        if (isMore) {
            refresh.finishLoadMore();
            mDataList.addAll(beanList);
        } else {
            refresh.finishRefresh();
            mDataList.clear();
            mDataList.addAll(beanList);
        }
        emptyWrapper.notifyDataSetChanged();
    }

    /**
     * 网络异常
     *
     * @param msg
     */
    @Override
    public void setNoNetwork(String msg) {
        refresh.finishRefresh();
        loadMask.setStatus(LoadingLayout.No_Network);
        loadMask.setNoNetworkText(msg);
        loadMask.setReloadButtonText("点击重试~~");
    }

    /**
     * 出错
     *
     * @param msg
     */
    @Override
    public void setError(String msg) {
        refresh.finishRefresh();
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setErrorText(msg);
        loadMask.setReloadButtonText("点击重试~~");
    }

    /**
     * 提示
     *
     * @param msg
     */
    @Override
    public void showMessage(String msg) {
        refresh.finishLoadMore();
        Toasty.normal(this, msg).show();
    }

    /**
     * 日志
     *
     * @param msg
     */
    @Override
    public void setLog(String msg) {
        refresh.finishLoadMore();
        Log.i("info", msg);
    }

//    class Adapter extends NineAdapter {
//
//        public Adapter(Context context, List<Image> list) {
//            super(context, list);
//        }
//
//        @Override
//        public int getCount() {
//            return (list == null) ? 0 : list.size();
//        }
//
//        @Override
//        public String getUrl(int position) {
//            return getItem(position) == null ? null : ((Image) getItem(position)).getUrl();
//        }
//
//        @Override
//        public Object getItem(int position) {
//            return (list == null) ? null : list.get(position);
//        }
//
//        @Override
//        public long getItemId(int position) {
//            return position;
//        }
//
//        @Override
//        public View getView(int i, View view) {
//            ImageView iv = new ImageView(context);
//            Glide.with(context)
//                    .load(list.get(i).getUrl())
//                    .apply(new RequestOptions().error(R.drawable.cover_normal_default).centerCrop().optionalTransform(new GlideRoundTransform(4)))
//                    .into(iv);
//            return iv;
//        }
//    }

//    //生成九宫格模型
//    private List<Image> initDatas(List<MeetingRoomListBean.Pictures> beanList) {
//        List<Image> images = new ArrayList<>();
//        for (int i = 0; i < beanList.size(); i++) {
//            images.add(new Image(beanList.get(i).getUrl(), 0, 0));
//        }
//
//        return images;
//    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case RESULT_OK:
                mPresenter.getMeetingList(streetId, "0");
                break;
            default:
                break;
        }
    }
}
